<template>
  <el-main class="content">
    <div class="login_container">
      <!-- 注册表单 -->
      <el-form ref="formRef" size="large" autocomplete="off" v-if="isRegister" :model="registerData" :rules="rules">
        <el-form-item style="align-content: center;">
          <h1>注册</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码"
                    v-model="registerData.password"></el-input>
        </el-form-item>
        <el-form-item prop="rePassword">
          <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码"
                    v-model="registerData.rePassword"></el-input>
        </el-form-item>
        <!-- 注册按钮 -->
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="submitForm2">
            注册
          </el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false;clearRegisterData()">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form  >

      <!-- 登录表单 -->
      <el-form ref="formRef" size="large" autocomplete="off" v-else :model="registerData" :rules="rules">
<!--        v-else: 这是Vue的条件渲染指令之一。它表示只有当前面的v-if或v-else-if条件不满足时，才会渲染这个<el-form>元素。注意，v-else必须紧跟在v-if或v-else-if之后，且只能用在它们之后。-->
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>
        <!-- 登录按钮 -->
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="submitForm1">登录</el-button>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-link type="primary" :underline="false" @click="isRegister = true;clearRegisterData()">
              注册 →
            </el-link>
            <el-link type="info" :underline="false" @click="returnHome">返回主页</el-link>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </el-main>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
//控制注册与登录表单的显示， 默认显示注册
import {ref} from "vue"
import {useRouter} from "vue-router"
import {userLoginService,userRegisterService} from "../api/User.js"
import {useTokenStore} from '../stores/token.js'


const isRegister = ref(false)

const router = useRouter()

//返回主页点击事件
const returnHome = () => {
  router.push('/layout')
}

//定义数据模型
const registerData = ref({
  username: '',
  password: '',
  rePassword: ''
})

//校验密码的函数
const checkRePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次确认密码'))
  } else if (value !== registerData.value.password) {
    callback(new Error('请确保两次输入的密码一样'))
  } else {
    callback()
  }
}

const formRef = ref(null);

//定义表单校验规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
  ],
  rePassword: [
    { validator: checkRePassword, trigger: 'blur' }
  ]
}



//定义函数,清空数据模型的数据
const clearRegisterData = ()=>{
  registerData.value={
    username:'',
    password:'',
    rePassword:''
  }
}

const tokenStore = useTokenStore();

// 登录表单提交
const submitForm1 = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 通过验证，执行提交操作
      // ElMessage.success('验证成功')
      // 在这里发出请求
      login()

    } else {
      ElMessage.error("验证失败")
      return false;

    }
  });
};

// 注册表单提交
const submitForm2 = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 通过验证，执行提交操作
      // ElMessage.success('验证成功')
      // 在这里发出请求
      register()

    } else {
      ElMessage.error("验证失败")
      return false;

    }
  });
};

//用户登录功能
const login = async ()=>{
  let result = await userLoginService(registerData.value)
  ElMessage.success(result.data?'登录成功':result.message)
  tokenStore.setToken(result.data)
  router.push('/')
}

//用户注册功能
const register = async () => {

  let result = await userRegisterService(registerData.value)

  isRegister.value = false

  ElMessage.success('注册成功!')

}

</script>

<style scoped>

.content{
  width: 100%;
  /*height: 100%;*/
  height: 940px;
  /*更换背景图片时,需要调整height*/
  /*background-image: url('../assets/images/LoginBackGround.png');*/
  background-image: url("../assets/images/img_6.png");
  background-size:100% ;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}
.login_container{
  width: 500px;
  height: 450px;
  /*background: rgba(223,219,219,0.2);*/
  /*background-color: white;*/
  background-color: rgba(255,255,255,0.7);/*rgba(255,255,255,0.7)这里的0.7表示不透明度*/
  border-radius: 5px;
  box-shadow: 0 25px 35px rgba(0,0,0,0.8);
  display: flex;
  align-items: center;
  justify-content: center;
}
.flex {
  width: 100%;
  display: flex;
  justify-content: space-between;
}


.el-button el-button--primary{
  height: 55px !important;
}

</style>